﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolLibrary.Entity.Person;

namespace SchoolLibrary.DataBase.DAO
{
    public class WriterDAO : AbstractDAO<Writer>
    {
        private static WriterDAO instance;

        private WriterDAO() { }

        public static WriterDAO getInstance()
        {
            if (instance == null)
            {
                instance = new WriterDAO();
            }
            return instance;
        }

        public List<Writer> findWritersByBookId(long id)
        {
            Query query = new Query(Writer.FIND_BOOK_WRITERS_BY_BOOK_ID);
            query.setParameter("bookId", id);
            return getDAOHelper().getResultList(query);
        }

        public override Writer findById(long id)
        {
            Query query = new Query(Writer.FIND_BY_ID);
            query.setParameter("id", id);
            return getDAOHelper().getSingleResult(query);
        }

        public override List<Writer> findAll()
        {
            Query query = new Query(Writer.FIND_ALL);
            return getDAOHelper().getResultList(query);
        }

        public override void save(Writer writer)
        {
            if (writer.Id != UNDIFINED_ID)
            {
                save(writer, Person.UPDATE);
            }
            else
            {
                save(writer, Person.SAVE);
            }
        }

        private void save(Person person, string queryString)
        {
            Query query = new Query(queryString);
            query.setParameter("id", person.Id);
            query.setStringParameter("tableName", Writer.TABLE_NAME);
            query.setParameter("name", person.Name);
            query.setParameter("middleName", person.MiddleName);
            query.setParameter("surname", person.Surname);
            getDAOHelper().executeUpdate(query);
        } 
    }
}
